package com.zy.mall.controller;

import com.google.gson.Gson;
import com.zy.mall.model.Admin;
import com.zy.mall.model.Result;
import com.zy.mall.model.bo.AdminChangeBo;
import com.zy.mall.model.bo.AdminLoginBo;
import com.zy.mall.model.bo.AdminSearchBo;
import com.zy.mall.model.vo.AdminLoginVo;
import com.zy.mall.service.AdminService;
import com.zy.mall.service.AdminServiceImpl;
import com.zy.mall.utils.HttpUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@WebServlet("/api/admin/admin/*")
public class AdminServlet extends HttpServlet {

    private AdminService adminService = new AdminServiceImpl();

    Gson gson = new Gson();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI(); //用这个API来区分不同请求（不同请求URL不一样）
        String action = requestURI.replace("/api/admin/admin/","");
        if("login".equals(action)){
            login(request, response);
        }else if("getSearchAdmins".equals(action)){
            getSearchAdmins(request, response);
        }else if("addAdminss".equals(action)){
            addAdmins(request, response);
        }else if ("updateAdminss".equals(action)){
            updateAdmins(request, response);
        }else if ("changePwd".equals(action)){
            changePwd(request, response);
        }
    }

    private void changePwd(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        AdminChangeBo changeBo = gson.fromJson(requestBody, AdminChangeBo.class);
        int code = adminService.changePwd(changeBo);
        if (code == 0) response.getWriter().println(gson.toJson(Result.ok()));
        if (code == 500) response.getWriter().println(gson.toJson(Result.error("请保证新密码一致")));
        if (code == 10000) response.getWriter().println(gson.toJson(Result.error("旧密码错误")));
    }

    private void updateAdmins(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        Admin admin = gson.fromJson(requestBody, Admin.class);
        boolean flag = adminService.updateAdmins(admin);
        Result result = new Result();
        if (!flag) {
            result.setCode(10000);
            result.setMessage("该账号不允许重复使用");
        } else {
            result.setCode(0);
        }
        response.getWriter().println(gson.toJson(result));
    }

    /**
     * 添加管理员
     * @param request
     * @param response
     */
    private void addAdmins(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        Admin admin = gson.fromJson(requestBody, Admin.class);
        adminService.addAdmin(admin);
        Result result = new Result();
        result.setCode(0);
        response.getWriter().println(gson.toJson(result));
    }

    /**
     * 条件查询管理员账户信息
     * @param request
     * @param response
     */
    private void getSearchAdmins(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        AdminSearchBo searchBo = gson.fromJson(requestBody, AdminSearchBo.class);
        List<Admin> admins = adminService.getSearchAdmins(searchBo);
        response.getWriter().println(gson.toJson(Result.ok(admins)));
    }


    /**
     * 管理员登录的业务逻辑
     * 1.浏览器向8084发请求，请求体中携带用户名密码参数 （json字符串）
     * 2.查数据库，校验密码
     * 3.响应
     * @param request
     * @param response
     */
    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //取出 请求体数据（不能用request.getParamater  只能获取key=value这种数据结构）
        String requestBody = HttpUtils.getRequestBody(request);
        AdminLoginBo loginBo = gson.fromJson(requestBody, AdminLoginBo.class);
        //System.out.println(loginBo);
        Admin login = adminService.login(loginBo);
        Result result = new Result();
        if(login != null){

            AdminLoginVo loginVo = new AdminLoginVo();
            loginVo.setToken(login.getNickname());
            loginVo.setName(login.getNickname());
            response.getWriter().println(gson.toJson(Result.ok(loginVo)));
        }else{
            response.getWriter().println(Result.error("用户名或密码错误"));
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI(); //用这个API来区分不同请求（不同请求URL不一样）
        String action = requestURI.replace("/api/admin/admin/","");
        if("allAdmins".equals(action)){
            allAdmins(request, response);
        }else if("deleteAdmins".equals(action)){
            String id = request.getParameter("id");
            deleteAdmins(id, request, response);
        }else if ("getAdminsInfo".equals(action)) {
            String id = request.getParameter("id");
            getAdminsInfo(id, request, response);
        }
    }

    private void getAdminsInfo(String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Admin admin = adminService.getAdminsInfo(id);
        Result result = new Result();
        if(admin != null){
            //返回正确的结果
            result.setCode(0);
            HashMap<Object, Object> map = new HashMap<>();
            map.put("id", admin.getId());
            map.put("email", admin.getEmail());
            map.put("nickname", admin.getNickname());
            map.put("pwd", admin.getPwd());
            result.setData(map);
        }else{
            //返回错误的信息 需要返回10000
            result.setCode(10000);
            result.setMessage("该用户不存在");
        }
        response.getWriter().println(gson.toJson(result));
    }

    private void deleteAdmins(String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        boolean flag = adminService.deleteAdmins(id);
        Result result = new Result();
        if (!flag) {
            result.setCode(10000);
        } else {
            result.setCode(0);
        }
        response.getWriter().println(gson.toJson(result));
    }

    /**
     * 显示所有账户信息
     * @param request
     * @param response
     */
    private void allAdmins(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Admin> adminList = adminService.allAdmins();
        Result result = new Result();
        result.setCode(0);
        result.setData(adminList);
        response.getWriter().println(gson.toJson(result));
    }
}
